import time
import requests
import json


# 请求需要发送的参数
headers = {
    'Cookie':'SINAGLOBAL=618919066387.7864.1624346401618; UOR=ilive.lenovo.com.cn,s.weibo.com,www.baidu.com; ULV=1715763314391:65:1:1:1143349720519.5286.1715763314389:1712387997847; ALF=1718355336; SUB=_2A25LQAjYDeRhGeBM7FMY9y_MzDqIHXVoPAQQrDV8PUJbkNANLUqtkW1NRNyWoXjoHBcQOlhuypndlHGIPpo7L3Ii; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WhTNAlv6EWJAXoS..AAr1Kh5JpX5KzhUgL.FoqES024S027S0q2dJLoI0qLxKBLB.zL1KqLxK-L12qLB-2LxKqL1KnLB-qLxKqL1-eL1h.LxKML1hzLBo.LxK-L1K2L1hqt; XSRF-TOKEN=kx5jb_9t1vvvNGwwNr6Kr188; WBPSESS=03Rwz19Z2C7dvXKIo40JJUonpHzzhP1JQuWdfXlDkW7M72rIIe3Dsnpc0CcHRu13qK4emuJBNXOZeSpXXJHkriVyy1YKZEonDTSo-rjRhqg4xNRJVtuC4E3udilWgTTC1Uf8Urb2BMmsXPp9XVJeNg==',
    'Referer':'https://weibo.com/u/7744301004?tabtype=album',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0'
}

def download(url):
    flag = 0
    resp = requests.get(url,headers = headers)
    json_data = resp.json()
    since_id = json_data['data']['since_id']
    if json_data['data']['since_id']:
        next_url = 'https://weibo.com/ajax/profile/getImageWall?uid=7744301004&sinceid={}'
        # 下一页的地址
        new_url = next_url.format(since_id)
        # print(new_url)
        with open('爬取文件/url.csv',mode='a',encoding='utf-8')as f:
            f.write(new_url+'\n')
            print('爬取',flag)
        time.sleep(2)
        download(new_url)
    return json_data


# 获取到pid,组成新的图片url,写入文件当中
def get_pid_url(json_data,url):
    album_list = json_data['data']['list']
    with open('爬取文件/weibo.csv',mode='w',encoding='utf-8') as f:
        for item in album_list:
            pid = item['pid']
            img_url = url.format(pid)
            f.write(img_url+'\n')
        print('写入完成')

# 下载图片
def get_img():
    offset = 0
    with open('爬取文件/weibo.txt',mode = 'r') as f:
        for url in f:
            url = url.strip()
            # print(url)
            img = requests.get(url,headers= headers).content
            time.sleep(1)
            with open('爬取文件/img/{}.jpg'.format(offset),mode='wb') as file:
                file.write(img)
                offset = offset + 1
    print('相册写入完成')

def main():
    # 开始的url
    url = 'https://weibo.com/ajax/profile/getImageWall?uid=7744301004&sinceid=0&has_album=true'
    img_url = 'https://wx3.sinaimg.cn/orj360/{}.jpg'


    json_data = download(url)
    print(json_data)
    # get_pid_url(json_data,img_url)
    # get_img()
    # get_next(json_data)


if __name__ == '__main__':
    main()